package lol.clann.bukkit.pluginboot.util;

import lol.clann.clannboot.annotation.inject.Inject;
import lol.clann.clannboot.annotation.svc.Service;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;

/**
 * @author pyz
 * @date 2018/8/5 上午8:31
 */
@Service(priority = Integer.MAX_VALUE)
public class LocationUtils {

    @Inject
    private WorldUtils worldUtils;
    @Inject
    private NBTCompoundUtils nbtCompoundUtils;

    /**
     * 通过InteractEvent获取放置方块的位置 InteractEvent先于BlockPlaceEvent触发
     * 直接判断BlockPlaceEvent可能会导致刷物品BUG，如领地刷UU，刷凋零等
     */
    public Location getLocationByBlockFace(Block block, BlockFace face) {
        Location loc = block.getLocation();
        if (face.equals(BlockFace.UP)) {
            loc = loc.add(0, 1, 0);
        } else if (face.equals(BlockFace.DOWN)) {
            loc = loc.add(0, -1, 0);
        } else if (face.equals(BlockFace.WEST)) {
            loc = loc.add(-1, 0, 0);
        } else if (face.equals(BlockFace.EAST)) {
            loc = loc.add(1, 0, 0);
        } else if (face.equals(BlockFace.SOUTH)) {
            loc = loc.add(0, 0, 1);
        } else if (face.equals(BlockFace.NORTH)) {
            loc = loc.add(0, 0, -1);
        }
        return loc;
    }

    /**
     * @param loc
     * @return nbtTag
     */
    public Object toCompound(Location loc) {
        Object tag = nbtCompoundUtils.newTagCompound();
        nbtCompoundUtils.setString(tag, "world", loc.getWorld().getName());
        nbtCompoundUtils.setDouble(tag, "x", loc.getX());
        nbtCompoundUtils.setDouble(tag, "y", loc.getX());
        nbtCompoundUtils.setDouble(tag, "z", loc.getX());
        nbtCompoundUtils.setFloat(tag, "pitch", loc.getPitch());
        nbtCompoundUtils.setFloat(tag, "yaw", loc.getYaw());
        return tag;
    }

    public Location fromCompound(Object nbtTag) {
        String world = nbtCompoundUtils.getString(nbtTag, "world");
        double x = nbtCompoundUtils.getDouble(nbtTag, "x");
        double y = nbtCompoundUtils.getDouble(nbtTag, "y");
        double z = nbtCompoundUtils.getDouble(nbtTag, "z");
        float pitch = nbtCompoundUtils.getFloat(nbtTag, "pitch");
        float yaw = nbtCompoundUtils.getFloat(nbtTag, "yaw");
        return new Location(worldUtils.getWorld(world), x, y, z, yaw, pitch);
    }

    public void fill(Location loc, Object nbtTag) {
        loc.setWorld(worldUtils.getWorld(nbtCompoundUtils.getString(nbtTag, "world")));
        loc.setX(nbtCompoundUtils.getDouble(nbtTag, "x"));
        loc.setY(nbtCompoundUtils.getDouble(nbtTag, "y"));
        loc.setZ(nbtCompoundUtils.getDouble(nbtTag, "z"));
        loc.setPitch(nbtCompoundUtils.getFloat(nbtTag, "pitch"));
        loc.setY(nbtCompoundUtils.getFloat(nbtTag, "yaw"));
    }

}
